import './public-path';
import { createApp } from 'vue';
import App from './App.vue';
import 'ant-design-vue/dist/antd.css';
import { setupRouter } from './router';
import '@/assets/styles/base/tailwind.css';
import initPlugins from '@/plugins';
import TjDesign from 'tj-design-vue';
import 'tj-design-vue/lib/index.css';
import '/src/util/iconfont';
import '/src/util/iconfont.css';
// import Vconsole from 'vconsole';
// new Vconsole();

let history;
let router;
let app;
let antd;
// 用于应用每次初始化时 判断当前是否属于被缓存状态，也就是说子应用只有第一次被加载时才会发送请求解析子应用
// 以后每次切换子应用都是从js的缓存中直接读取
// 除非 micro-app的destroy是true的情况下 每次切换子应用都会重新加载资源进行初始化
let isCached = false;

function mount() {
  const { router: _router, history: _history } = setupRouter();
  history = _history;
  router = _router;
  app = createApp(App);
  initPlugins(app);
  app.use(antd);
  app.use(router);
  app.use(TjDesign);
  app.mount('#micro-app-info-system');
  // console.log('main');

  if (window.__MICRO_APP_ENVIRONMENT__) {
    // 全局监听函数
    window.microApp.addGlobalDataListener(({ data, methods, appName } = {}) => {
      console.log(data, '数据');
    }, true);

    // 独立的监听函数 监听当前自身（子应用）与基座的通信
    window.microApp.addDataListener((data = {}) => {
      console.log(11);
    }, true);
  } else {
    // 本地开发数据
    console.log(2);
  }
}

function unmount() {
  app.unmount();
  history.destroy();
  history = null;
  router = null;
  app = null;
  isCached = true;
  window.microApp.clearGlobalDataListener();
}

if (window.__MICRO_APP_ENVIRONMENT__) {
  initMicroApp();
} else {
  mount();
}

function initMicroApp() {
  window[`micro-app-${window.__MICRO_APP_NAME__}`] = {
    mount,
    unmount
  };
}
